using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Threading.Tasks;
using System.Windows.Input;
using System.Runtime.CompilerServices;
using System.Linq;
using WPF_MVVM_Test.MVVM_Model.ProductionOrder;
using WPF_MVVM_Test.MVVM_Model.Process;
using WPF_MVVM_Test.Services.ProductionOrder;
using WPF_MVVM_Test.MVVM_Services;
using WPF_MVVM_Test.MVVM_ViewModel;
using ProductionOrderService = WPF_MVVM_Test.Services.ProductionOrder.ProductionOrderService;
using System.Windows; // Added for MessageBox
using System.Collections.Generic; // Added for Dictionary
using WorkOrderTaskRequest = WPF_MVVM_Test.MVVM_Model.Process.WorkOrderTaskRequest;
using BatchAddWorkOrderTasksRequest = WPF_MVVM_Test.MVVM_Model.Process.BatchAddWorkOrderTasksRequest;
using BatchAddWorkOrderTasksDtoRequest = WPF_MVVM_Test.MVVM_Model.Process.BatchAddWorkOrderTasksDtoRequest;
using UpdateProductionOrderStatusRequest = WPF_MVVM_Test.MVVM_Model.ProductionOrder.UpdateProductionOrderStatusRequest;

namespace WPF_MVVM_Test.MVVM_ViewModel.ProductionOrder
{
    public class ScheduleProductionDialogViewModel : INotifyPropertyChanged
    {
        private readonly ProductionOrderService _productionOrderService;
        private readonly ProcessService _processService;
        private readonly ProductionOrderModel _originalOrder;
        private bool _dialogResult;
        private string _orderNumber = string.Empty;
        private string _orderName = string.Empty;
        private string _productNumber = string.Empty;
        private string _specification = string.Empty;
        private string _unit = string.Empty;
        private string _bomCode = string.Empty;
        private decimal _planQuantity;
        private DateTime _planStartTime = DateTime.Today;
        private DateTime _planEndTime = DateTime.Today.AddDays(7);
        private string _remark = string.Empty;
        private ProcessStepModel? _selectedProcessStep;
        private string _processRouteNumber = string.Empty;
        private string _processRouteName = string.Empty;

        // 添加字典来跟踪每个工序的任务
        private readonly Dictionary<string, ObservableCollection<ProcessTaskModel>> _tasksByProcessStep = new Dictionary<string, ObservableCollection<ProcessTaskModel>>();

        public ScheduleProductionDialogViewModel(ProductionOrderModel order)
        {
            _originalOrder = order;
            _productionOrderService = new ProductionOrderService();
            _processService = new ProcessService();
            
            // 填充基础信息
            FillBasicInfo();
            
            // 加载工序数据
            _ = LoadProcessStepsAsync();
            // 加载工艺路线信息
            _ = LoadProcessRoutingAsync();
            // 加载物料清单
            _ = LoadMaterialsAsync();
            InitializeCommands();
        }

        #region 基础信息属性（只读）
        public string OrderNumber
        {
            get => _orderNumber;
            set { _orderNumber = value; OnPropertyChanged(); }
        }

        public string OrderName
        {
            get => _orderName;
            set { _orderName = value; OnPropertyChanged(); }
        }

        // 添加ProductName属性以匹配界面绑定
        public string ProductName
        {
            get => _orderName; // 工单名称通常就是产品名称
            set { _orderName = value; OnPropertyChanged(); OnPropertyChanged(nameof(OrderName)); }
        }

        public string ProductNumber
        {
            get => _productNumber;
            set { _productNumber = value; OnPropertyChanged(); }
        }

        public string Specification
        {
            get => _specification;
            set { _specification = value; OnPropertyChanged(); }
        }

        public string Unit
        {
            get => _unit;
            set { _unit = value; OnPropertyChanged(); }
        }

        public string BomCode
        {
            get => _bomCode;
            set { _bomCode = value; OnPropertyChanged(); }
        }
        #endregion

        #region 排产信息属性（可编辑）
        public decimal PlanQuantity
        {
            get => _planQuantity;
            set { _planQuantity = value; OnPropertyChanged(); }
        }

        // 添加StartTime和EndTime属性以匹配界面绑定
        public DateTime StartTime
        {
            get => _planStartTime;
            set { _planStartTime = value; OnPropertyChanged(); OnPropertyChanged(nameof(PlanStartTime)); }
        }

        public DateTime EndTime
        {
            get => _planEndTime;
            set { _planEndTime = value; OnPropertyChanged(); OnPropertyChanged(nameof(PlanEndTime)); }
        }

        public DateTime PlanStartTime
        {
            get => _planStartTime;
            set { _planStartTime = value; OnPropertyChanged(); OnPropertyChanged(nameof(StartTime)); }
        }

        public DateTime PlanEndTime
        {
            get => _planEndTime;
            set { _planEndTime = value; OnPropertyChanged(); OnPropertyChanged(nameof(EndTime)); }
        }

        public string Remark
        {
            get => _remark;
            set { _remark = value; OnPropertyChanged(); }
        }
        #endregion

        #region 工艺路线属性
        /// <summary>
        /// 工艺路线编号
        /// </summary>
        public string ProcessRouteNumber
        {
            get => _processRouteNumber;
            set { _processRouteNumber = value; OnPropertyChanged(); }
        }

        /// <summary>
        /// 工艺路线名称
        /// </summary>
        public string ProcessRouteName
        {
            get => _processRouteName;
            set { _processRouteName = value; OnPropertyChanged(); }
        }
        #endregion

        #region 工艺流程属性
        /// <summary>
        /// 工序列表
        /// </summary>
        public ObservableCollection<ProcessStepModel> ProcessSteps { get; set; } = new ObservableCollection<ProcessStepModel>();

        /// <summary>
        /// 当前选中的工序
        /// </summary>
        public ProcessStepModel? SelectedProcessStep
        {
            get => _selectedProcessStep;
            set
            {
                if (_selectedProcessStep != value)
                {
                    _selectedProcessStep = value;
                    OnPropertyChanged();
                }
            }
        }

        /// <summary>
        /// 任务列表
        /// </summary>
        public ObservableCollection<ProcessTaskModel> Tasks { get; set; } = new ObservableCollection<ProcessTaskModel>();
        #endregion

        #region 命令
        public ICommand SelectProcessStepCommand { get; private set; } = null!;
        public ICommand ConfirmCommand { get; private set; } = null!;
        public ICommand CancelCommand { get; private set; } = null!;
        public ICommand AddTaskCommand { get; private set; } = null!;
        public ICommand EditTaskCommand { get; private set; } = null!;
        public ICommand DeleteTaskCommand { get; private set; } = null!;
        public ICommand TestApiCommand { get; private set; } = null!; // 添加测试命令
        public ICommand DirectTestApiCommand { get; private set; } = null!; // 添加直接测试命令
        public ICommand ShowTaskStatisticsCommand { get; private set; } = null!; // 添加任务统计命令
        public ICommand CheckDataFieldsCommand { get; private set; } = null!; // 添加数据字段检查命令
        public ICommand CheckTaskDictionaryCommand { get; private set; } = null!; // 添加任务字典检查命令
        public ICommand PreviewDataCommand { get; private set; } = null!; // 添加数据预览命令

        private void InitializeCommands()
        {
            SelectProcessStepCommand = new RelayCommand<ProcessStepModel>(SelectProcessStep);
            ConfirmCommand = new RelayCommand(ConfirmSchedule);
            CancelCommand = new RelayCommand(CancelSchedule);
            AddTaskCommand = new RelayCommand(AddTask);
            EditTaskCommand = new RelayCommand<ProcessTaskModel>(EditTask);
            DeleteTaskCommand = new RelayCommand<ProcessTaskModel>(DeleteTask);
            TestApiCommand = new RelayCommand(TestApiCall); // 初始化测试命令
            DirectTestApiCommand = new RelayCommand(DirectTestApiCall); // 初始化直接测试命令
            ShowTaskStatisticsCommand = new RelayCommand(ShowTaskDataStatistics); // 初始化任务统计命令
            CheckDataFieldsCommand = new RelayCommand(CheckDataFields); // 初始化数据字段检查命令
            CheckTaskDictionaryCommand = new RelayCommand(CheckTaskDictionary); // 初始化任务字典检查命令
            PreviewDataCommand = new RelayCommand(PreviewData); // 初始化数据预览命令
        }

        private void SelectProcessStep(ProcessStepModel? processStep)
        {
            if (processStep == null) return;

            // 保存当前工序的任务到字典中（在切换之前）
            if (SelectedProcessStep != null)
            {
                _tasksByProcessStep[SelectedProcessStep.Id] = new ObservableCollection<ProcessTaskModel>(Tasks);
            }

            // 更新选中状态
            foreach (var step in ProcessSteps)
            {
                step.IsSelected = (step == processStep);
            }
            
            SelectedProcessStep = processStep;

            // 加载目标工序的任务
            LoadTasksForProcessStep(processStep.Id);
        }

        private async void LoadTasksForProcessStep(string processStepId)
        {
            // 如果字典中已有该工序的任务，直接使用
            if (_tasksByProcessStep.ContainsKey(processStepId))
            {
                Tasks.Clear();
                foreach (var task in _tasksByProcessStep[processStepId])
                {
                    Tasks.Add(task);
                }
            }
            else
            {
                // 否则从API加载
                await LoadTasksAsync();
                
                // 将加载的任务保存到字典中
                _tasksByProcessStep[processStepId] = new ObservableCollection<ProcessTaskModel>(Tasks);
            }
        }

        private async void ConfirmSchedule()
        {
            try
            {
                // 数据验证
                if (string.IsNullOrEmpty(_originalOrder.Id))
                {
                    System.Windows.MessageBox.Show("生产工单ID不能为空", "验证错误", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Warning);
                    return;
                }

                // 收集所有工序的任务数据
                var allTasks = new List<WorkOrderTaskRequest>();
                
                System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] 开始收集任务数据");
                System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] 工序数量: {ProcessSteps.Count}");
                System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] 生产工单ID: {_originalOrder.Id}");
                System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] 工艺路线编号: {ProcessRouteNumber}");
                System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] 工艺路线名称: {ProcessRouteName}");
                
                foreach (var processStep in ProcessSteps)
                {
                    System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] 处理工序: {processStep.ProcessStepName} (ID: {processStep.Id})");
                    
                    if (_tasksByProcessStep.ContainsKey(processStep.Id))
                    {
                        var tasks = _tasksByProcessStep[processStep.Id];
                        System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] 工序 {processStep.ProcessStepName} 的任务数量: {tasks.Count}");
                        
                        foreach (var task in tasks)
                        {
                            // 确保时间字段有有效值
                            var planStartTime = task.PlannedStartTime ?? PlanStartTime;
                            var planEndTime = task.PlannedEndTime ?? PlanEndTime;
                            
                            // 如果结束时间早于开始时间，调整结束时间
                            if (planEndTime <= planStartTime)
                            {
                                planEndTime = planStartTime.AddHours(1);
                            }

                            // 验证GUID字段
                            var processRouteId = Guid.TryParse(ProcessRouteNumber, out var routeGuid) ? routeGuid : Guid.NewGuid();
                            var processStepId = Guid.TryParse(processStep.Id, out var stepGuid) ? stepGuid : Guid.NewGuid();

                            // 计算计划时长（小时）
                            var planDuration = (decimal)(planEndTime - planStartTime).TotalHours;
                            if (planDuration <= 0)
                            {
                                planDuration = 1.0m; // 默认1小时
                            }

                            var workOrderTask = new WorkOrderTaskRequest
                            {
                                SequenceNumber = task.SequenceNo,
                                TaskNumber = string.IsNullOrEmpty(task.TaskId) ? $"TASK_{processStep.Id}_{DateTime.Now:yyyyMMddHHmmss}" : task.TaskId,
                                TaskName = string.IsNullOrEmpty(task.TaskName) ? $"{processStep.ProcessStepName}任务" : task.TaskName,
                                ProductionOrderId = _originalOrder.Id,
                                StationName = string.IsNullOrEmpty(task.StationName) ? "默认工位" : task.StationName,
                                ProcessCode = processStep.ProcessStepName,
                                ProcessName = processStep.ProcessStepName,
                                ProcessFlow = string.IsNullOrEmpty(ProcessRouteName) ? "默认工艺流程" : ProcessRouteName,
                                ProcessType = string.IsNullOrEmpty(task.ProcessType) ? "默认类型" : task.ProcessType,
                                TaskColor = string.IsNullOrEmpty(task.TaskColor) ? "#1890FF" : task.TaskColor,
                                PlanQuantity = task.PlannedQuantity > 0 ? task.PlannedQuantity : PlanQuantity,
                                PlanStartTime = planStartTime,
                                PlanEndTime = planEndTime,
                                PlanDuration = planDuration,
                                Status = string.IsNullOrEmpty(task.Status) ? "待开工" : task.Status,
                                ProcessRouteId = processRouteId,
                                ProcessStepId = processStepId,
                                Priority = task.Priority > 0 ? task.Priority : 4,
                                Remarks = string.IsNullOrEmpty(task.Remarks) ? Remark : task.Remarks
                            };
                            
                            // 验证任务数据
                            if (!ValidateTaskData(workOrderTask))
                            {
                                System.Windows.MessageBox.Show($"任务数据验证失败: {workOrderTask.TaskName}", "验证错误", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Warning);
                                return;
                            }
                            
                            allTasks.Add(workOrderTask);
                            System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] 添加任务: {workOrderTask.TaskName} (编号: {workOrderTask.TaskNumber})");
                        }
                    }
                    else
                    {
                        System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] 工序 {processStep.ProcessStepName} 没有任务数据");
                    }
                }

                System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] 总任务数量: {allTasks.Count}");

                if (allTasks.Count == 0)
                {
                    // 如果没有任务数据，创建默认任务
                    System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] 没有任务数据，创建默认任务");
                    System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] 工序数量: {ProcessSteps.Count}");
                    
                    foreach (var processStep in ProcessSteps)
                    {
                        System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] 为工序 {processStep.ProcessStepName} (ID: {processStep.Id}) 创建默认任务");
                        
                        var processRouteId = Guid.TryParse(ProcessRouteNumber, out var routeGuid) ? routeGuid : Guid.NewGuid();
                        var processStepId = Guid.TryParse(processStep.Id, out var stepGuid) ? stepGuid : Guid.NewGuid();
                        
                        // 计算计划时长（小时）
                        var planDuration = (decimal)(PlanEndTime - PlanStartTime).TotalHours;
                        if (planDuration <= 0)
                        {
                            planDuration = 1.0m; // 默认1小时
                        }
                        
                        var defaultTask = new WorkOrderTaskRequest
                        {
                            SequenceNumber = allTasks.Count + 1,
                            TaskNumber = $"TASK_{processStep.Id}_{DateTime.Now:yyyyMMddHHmmss}",
                            TaskName = $"{processStep.ProcessStepName}任务",
                            ProductionOrderId = _originalOrder.Id,
                            StationName = "默认工位",
                            ProcessCode = processStep.ProcessStepName,
                            ProcessName = processStep.ProcessStepName,
                            ProcessFlow = string.IsNullOrEmpty(ProcessRouteName) ? "默认工艺流程" : ProcessRouteName,
                            ProcessType = "默认类型",
                            TaskColor = "#1890FF",
                            PlanQuantity = PlanQuantity,
                            PlanStartTime = PlanStartTime,
                            PlanEndTime = PlanEndTime,
                            PlanDuration = planDuration,
                            Status = "待开工",
                            ProcessRouteId = processRouteId,
                            ProcessStepId = processStepId,
                            Priority = 4,
                            Remarks = "系统自动生成的默认任务"
                        };
                        
                        // 验证默认任务数据
                        if (!ValidateTaskData(defaultTask))
                        {
                            System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] 默认任务验证失败: {defaultTask.TaskName}");
                            System.Windows.MessageBox.Show($"默认任务数据验证失败: {defaultTask.TaskName}", "验证错误", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Warning);
                            return;
                        }
                        
                        allTasks.Add(defaultTask);
                        System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] 创建默认任务成功: {defaultTask.TaskName} (编号: {defaultTask.TaskNumber})");
                    }
                    
                    System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] 默认任务创建完成，总任务数: {allTasks.Count}");
                }

                if (allTasks.Count == 0)
                {
                    System.Windows.MessageBox.Show("没有任务数据需要保存", "提示", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Information);
                    return;
                }

                // 验证所有任务数据
                foreach (var task in allTasks)
                {
                    if (!ValidateTaskData(task))
                    {
                        System.Windows.MessageBox.Show($"任务数据验证失败: {task.TaskName}", "验证错误", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Warning);
                        return;
                    }
                }

                // 创建批量添加请求
                var batchRequest = new BatchAddWorkOrderTasksRequest
                {
                    Tasks = allTasks
                };

                // 显示确认对话框
                var confirmResult = System.Windows.MessageBox.Show(
                    $"确定要批量添加 {allTasks.Count} 个任务吗？", 
                    "确认排产", 
                    System.Windows.MessageBoxButton.YesNo, 
                    System.Windows.MessageBoxImage.Question);

                if (confirmResult != System.Windows.MessageBoxResult.Yes)
                {
                    return;
                }

                // 调用批量添加API - 直接使用batchRequest，不使用DTO包装
                System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] === 开始API调用 ===");
                System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] 发送任务数量: {allTasks.Count}");
                
                // 记录每个任务的详细信息
                for (int i = 0; i < allTasks.Count; i++)
                {
                    var task = allTasks[i];
                    System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] 任务 {i + 1}:");
                    System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}]   序号: {task.SequenceNumber}");
                    System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}]   任务编号: {task.TaskNumber}");
                    System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}]   任务名称: {task.TaskName}");
                    System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}]   生产工单ID: {task.ProductionOrderId}");
                    System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}]   工位名称: {task.StationName}");
                    System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}]   工序代码: {task.ProcessCode}");
                    System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}]   工序名称: {task.ProcessName}");
                    System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}]   工艺流程: {task.ProcessFlow}");
                    System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}]   工序类型: {task.ProcessType}");
                    System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}]   任务颜色: {task.TaskColor}");
                    System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}]   计划数量: {task.PlanQuantity}");
                    System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}]   计划开始时间: {task.PlanStartTime}");
                    System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}]   计划结束时间: {task.PlanEndTime}");
                    System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}]   计划时长: {task.PlanDuration}");
                    System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}]   状态: {task.Status}");
                    System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}]   工艺路线ID: {task.ProcessRouteId}");
                    System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}]   工序步骤ID: {task.ProcessStepId}");
                    System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}]   优先级: {task.Priority}");
                    System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}]   备注: {task.Remarks}");
                }
                
                var response = await _processService.BatchAddWorkOrderTasksAsync(batchRequest);
                
                System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] API响应:");
                System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}]   IsSuc: {response.IsSuc}");
                System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}]   Code: {response.Code}");
                System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}]   Msg: {response.Msg}");
                System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] === API调用结束 ===");

                if (response.IsSuc)
                {
                    System.Windows.MessageBox.Show($"成功保存 {allTasks.Count} 个任务", "成功", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Information);
                    
                    // 调用更新生产工单状态API
                    await UpdateProductionOrderStatus();
                    
                    // 设置对话框结果为成功，自动关闭弹窗
                    System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] 排产成功，准备关闭弹窗");
                    System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] 当前DialogResult: {DialogResult}");
                    DialogResult = true;
                    System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] 设置DialogResult为true完成");
                }
                else
                {
                    System.Windows.MessageBox.Show($"保存失败: {response.Msg}", "错误", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Error);
                }
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show($"保存任务时发生错误: {ex.Message}", "错误", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// 更新生产工单状态
        /// </summary>
        private async Task UpdateProductionOrderStatus()
        {
            try
            {
                System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] === 开始更新生产工单状态 ===");
                System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] 生产工单ID: {_originalOrder.Id}");
                
                var updateStatusRequest = new UpdateProductionOrderStatusRequest
                {
                    Id = _originalOrder.Id,
                    Status = "进行中", // 排产完成后状态改为"进行中"
                    UpdatedBy = "系统用户" // 可以根据实际需要设置更新人
                };
                
                System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] 更新状态请求:");
                System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}]   ID: {updateStatusRequest.Id}");
                System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}]   Status: {updateStatusRequest.Status}");
                System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}]   UpdatedBy: {updateStatusRequest.UpdatedBy}");
                
                var response = await _productionOrderService.UpdateProductionOrderStatusAsync(updateStatusRequest);
                
                System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] 更新状态API响应:");
                System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}]   IsSuc: {response.Success}");
                System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}]   Code: {response.Code}");
                System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}]   Msg: {response.Message}");
                System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] === 更新状态结束 ===");
                
                if (response.Success)
                {
                    System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] 生产工单状态更新成功");
                }
                else
                {
                    System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] 生产工单状态更新失败: {response.Message}");
                    // 注意：这里不显示错误消息给用户，因为任务已经成功保存
                    // 状态更新失败不影响排产的成功
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] 更新生产工单状态异常: {ex.Message}");
                // 注意：这里不显示错误消息给用户，因为任务已经成功保存
                // 状态更新异常不影响排产的成功
            }
        }

        private void CancelSchedule()
        {
            // 直接设置对话框结果为取消，关闭弹窗
            System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] 用户点击取消按钮，准备关闭弹窗");
            System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] 当前DialogResult: {DialogResult}");
            DialogResult = false;
            System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] 设置DialogResult为false完成");
        }

        /// <summary>
        /// 测试API调用方法
        /// </summary>
        private async void TestApiCall()
        {
            try
            {
                // 创建测试数据，完全匹配curl命令中的数据结构
                var testTask = new WorkOrderTaskRequest
                {
                    SequenceNumber = 1,
                    TaskNumber = "TEST_TASK_001",
                    TaskName = "测试任务",
                    ProductionOrderId = _originalOrder.Id,
                    StationName = "测试工位",
                    ProcessCode = "TEST_PROCESS",
                    ProcessName = "测试工序",
                    ProcessFlow = "测试工艺流程",
                    ProcessType = "测试类型",
                    TaskColor = "#1890FF",
                    PlanQuantity = 100.0m,
                    PlanStartTime = DateTime.Now,
                    PlanEndTime = DateTime.Now.AddHours(2),
                    PlanDuration = 2.0m,
                    Status = "待开工",
                    ProcessRouteId = Guid.Parse("3fa85f64-5717-4562-b3fc-2c963f66afa6"),
                    ProcessStepId = Guid.Parse("3fa85f64-5717-4562-b3fc-2c963f66afa6"),
                    Priority = 4,
                    Remarks = "测试任务备注"
                };

                var testBatchRequest = new BatchAddWorkOrderTasksRequest
                {
                    Tasks = new List<WorkOrderTaskRequest> { testTask }
                };

                // 验证JSON序列化格式
                var jsonOptions = new System.Text.Json.JsonSerializerOptions
                {
                    PropertyNamingPolicy = System.Text.Json.JsonNamingPolicy.CamelCase,
                    WriteIndented = true
                };
                var jsonString = System.Text.Json.JsonSerializer.Serialize(testBatchRequest, jsonOptions);
                
                System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] 测试数据JSON格式:");
                System.Diagnostics.Debug.WriteLine(jsonString);

                System.Windows.MessageBox.Show("开始测试API调用...", "测试", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Information);

                // 调用API - 直接使用testBatchRequest，不使用DTO包装
                var response = await _processService.BatchAddWorkOrderTasksAsync(testBatchRequest);

                if (response.IsSuc)
                {
                    System.Windows.MessageBox.Show("API测试成功！", "成功", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Information);
                }
                else
                {
                    System.Windows.MessageBox.Show($"API测试失败: {response.Msg}", "失败", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Error);
                }
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show($"API测试异常: {ex.Message}", "异常", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// 直接测试API调用方法
        /// </summary>
        private async void DirectTestApiCall()
        {
            try
            {
                using var httpClient = new System.Net.Http.HttpClient();
                httpClient.BaseAddress = new Uri("http://8.140.242.140:8888/");
                httpClient.DefaultRequestHeaders.Add("Accept", "text/plain");

                // 创建与curl命令完全一致的JSON数据 - 不使用dto包装
                var jsonData = @"{
  ""tasks"": [
    {
      ""sequenceNumber"": 1,
      ""taskNumber"": ""TEST_TASK_001"",
      ""taskName"": ""测试任务"",
      ""productionOrderId"": """ + _originalOrder.Id + @""",
      ""stationName"": ""测试工位"",
      ""processCode"": ""TEST_PROCESS"",
      ""processName"": ""测试工序"",
      ""processFlow"": ""测试工艺流程"",
      ""processType"": ""测试类型"",
      ""taskColor"": ""#1890FF"",
      ""planQuantity"": 100.0,
      ""planStartTime"": """ + DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss.fffZ") + @""",
      ""planEndTime"": """ + DateTime.Now.AddHours(2).ToString("yyyy-MM-ddTHH:mm:ss.fffZ") + @""",
      ""planDuration"": 2.0,
      ""status"": ""待开工"",
      ""processRouteId"": ""3fa85f64-5717-4562-b3fc-2c963f66afa6"",
      ""processStepId"": ""3fa85f64-5717-4562-b3fc-2c963f66afa6"",
      ""priority"": 4,
      ""remarks"": ""测试任务备注""
    }
  ]
}";

                System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] 直接测试API调用");
                System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] 请求数据: {jsonData}");

                var content = new System.Net.Http.StringContent(jsonData, System.Text.Encoding.UTF8, "application/json");
                var response = await httpClient.PostAsync("api/ProductionOrder/BatchAddWorkOrderTasks/work-order-tasks/batch", content);

                var responseContent = await response.Content.ReadAsStringAsync();
                System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] 响应状态码: {response.StatusCode}");
                System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] 响应内容: {responseContent}");

                if (response.IsSuccessStatusCode)
                {
                    System.Windows.MessageBox.Show("直接API测试成功！", "成功", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Information);
                }
                else
                {
                    System.Windows.MessageBox.Show($"直接API测试失败: {response.StatusCode} - {responseContent}", "失败", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Error);
                }
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show($"直接API测试异常: {ex.Message}", "异常", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// 验证任务数据完整性
        /// </summary>
        /// <param name="task">任务数据</param>
        /// <returns>验证结果</returns>
        private bool ValidateTaskData(WorkOrderTaskRequest task)
        {
            System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] 验证任务数据: {task.TaskName}");
            System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] TaskNumber: {task.TaskNumber}");
            System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] TaskName: {task.TaskName}");
            System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] ProductionOrderId: {task.ProductionOrderId}");
            System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] StationName: {task.StationName}");
            System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] ProcessCode: {task.ProcessCode}");
            System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] ProcessName: {task.ProcessName}");
            System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] ProcessFlow: {task.ProcessFlow}");
            System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] ProcessType: {task.ProcessType}");
            System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] TaskColor: {task.TaskColor}");
            System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] PlanQuantity: {task.PlanQuantity}");
            System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] PlanStartTime: {task.PlanStartTime}");
            System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] PlanEndTime: {task.PlanEndTime}");
            System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] PlanDuration: {task.PlanDuration}");
            System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] Status: {task.Status}");
            System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] ProcessRouteId: {task.ProcessRouteId}");
            System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] ProcessStepId: {task.ProcessStepId}");
            System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] Priority: {task.Priority}");
            System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] Remarks: {task.Remarks}");

            if (string.IsNullOrEmpty(task.TaskNumber))
            {
                System.Windows.MessageBox.Show("任务编号不能为空", "验证错误", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Warning);
                return false;
            }

            if (string.IsNullOrEmpty(task.TaskName))
            {
                System.Windows.MessageBox.Show("任务名称不能为空", "验证错误", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Warning);
                return false;
            }

            if (string.IsNullOrEmpty(task.ProductionOrderId))
            {
                System.Windows.MessageBox.Show("生产工单ID不能为空", "验证错误", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Warning);
                return false;
            }

            if (string.IsNullOrEmpty(task.StationName))
            {
                System.Windows.MessageBox.Show("工位名称不能为空", "验证错误", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Warning);
                return false;
            }

            if (string.IsNullOrEmpty(task.ProcessCode))
            {
                System.Windows.MessageBox.Show("工序代码不能为空", "验证错误", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Warning);
                return false;
            }

            if (string.IsNullOrEmpty(task.ProcessName))
            {
                System.Windows.MessageBox.Show("工序名称不能为空", "验证错误", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Warning);
                return false;
            }

            if (string.IsNullOrEmpty(task.ProcessFlow))
            {
                System.Windows.MessageBox.Show("工艺流程不能为空", "验证错误", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Warning);
                return false;
            }

            if (string.IsNullOrEmpty(task.ProcessType))
            {
                System.Windows.MessageBox.Show("工序类型不能为空", "验证错误", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Warning);
                return false;
            }

            if (string.IsNullOrEmpty(task.TaskColor))
            {
                System.Windows.MessageBox.Show("任务颜色不能为空", "验证错误", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Warning);
                return false;
            }

            if (task.PlanQuantity <= 0)
            {
                System.Windows.MessageBox.Show("计划数量必须大于0", "验证错误", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Warning);
                return false;
            }

            if (task.PlanStartTime >= task.PlanEndTime)
            {
                System.Windows.MessageBox.Show("计划开始时间必须早于结束时间", "验证错误", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Warning);
                return false;
            }

            if (task.PlanDuration <= 0)
            {
                System.Windows.MessageBox.Show("计划时长必须大于0", "验证错误", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Warning);
                return false;
            }

            if (string.IsNullOrEmpty(task.Status))
            {
                System.Windows.MessageBox.Show("任务状态不能为空", "验证错误", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Warning);
                return false;
            }

            if (task.ProcessRouteId == null || task.ProcessRouteId == Guid.Empty)
            {
                System.Windows.MessageBox.Show("工艺路线ID不能为空", "验证错误", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Warning);
                return false;
            }

            if (task.ProcessStepId == null || task.ProcessStepId == Guid.Empty)
            {
                System.Windows.MessageBox.Show("工序步骤ID不能为空", "验证错误", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Warning);
                return false;
            }

            if (task.Priority <= 0)
            {
                System.Windows.MessageBox.Show("优先级必须大于0", "验证错误", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Warning);
                return false;
            }

            System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] 任务数据验证通过: {task.TaskName}");
            return true;
        }

        /// <summary>
        /// 显示任务数据统计信息
        /// </summary>
        private void ShowTaskDataStatistics()
        {
            var totalTasks = 0;
            var taskDetails = new List<string>();

            System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] === 任务数据统计开始 ===");
            System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] 工序总数: {ProcessSteps.Count}");
            System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] 任务字典键数量: {_tasksByProcessStep.Count}");

            foreach (var processStep in ProcessSteps)
            {
                System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] 检查工序: {processStep.ProcessStepName} (ID: {processStep.Id})");
                
                if (_tasksByProcessStep.ContainsKey(processStep.Id))
                {
                    var tasks = _tasksByProcessStep[processStep.Id];
                    totalTasks += tasks.Count;
                    taskDetails.Add($"{processStep.ProcessStepName}: {tasks.Count} 个任务");
                    System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] 工序 {processStep.ProcessStepName} 有 {tasks.Count} 个任务");
                    
                    // 详细输出每个任务的信息
                    for (int i = 0; i < tasks.Count; i++)
                    {
                        var task = tasks[i];
                        System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}]   任务 {i + 1}: ID={task.TaskId}, 名称={task.TaskName}, 工位={task.StationName}");
                    }
                }
                else
                {
                    taskDetails.Add($"{processStep.ProcessStepName}: 0 个任务");
                    System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] 工序 {processStep.ProcessStepName} 没有任务数据");
                }
            }

            System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] 总任务数: {totalTasks}");
            System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] === 任务数据统计结束 ===");

            var message = $"任务数据统计:\n总任务数: {totalTasks}\n\n详细统计:\n{string.Join("\n", taskDetails)}";
            System.Windows.MessageBox.Show(message, "任务数据统计", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Information);
        }

        /// <summary>
        /// 检查数据字段完整性
        /// </summary>
        private void CheckDataFields()
        {
            var issues = new List<string>();

            // 检查基础信息
            if (string.IsNullOrEmpty(_originalOrder.Id))
                issues.Add("生产工单ID为空");
            
            if (string.IsNullOrEmpty(ProcessRouteNumber))
                issues.Add("工艺路线编号为空");
            
            if (string.IsNullOrEmpty(ProcessRouteName))
                issues.Add("工艺路线名称为空");

            // 检查工序数据
            if (ProcessSteps.Count == 0)
                issues.Add("工序列表为空");
            else
            {
                foreach (var step in ProcessSteps)
                {
                    if (string.IsNullOrEmpty(step.Id))
                        issues.Add($"工序 {step.ProcessStepName} 的ID为空");
                    
                    if (string.IsNullOrEmpty(step.ProcessStepName))
                        issues.Add($"工序ID {step.Id} 的名称为空");
                }
            }

            // 检查任务数据
            var totalTasks = 0;
            foreach (var processStep in ProcessSteps)
            {
                if (_tasksByProcessStep.ContainsKey(processStep.Id))
                {
                    var tasks = _tasksByProcessStep[processStep.Id];
                    totalTasks += tasks.Count;
                    
                    foreach (var task in tasks)
                    {
                        if (string.IsNullOrEmpty(task.TaskId))
                            issues.Add($"工序 {processStep.ProcessStepName} 的任务编号为空");
                        
                        if (string.IsNullOrEmpty(task.TaskName))
                            issues.Add($"工序 {processStep.ProcessStepName} 的任务名称为空");
                        
                        if (string.IsNullOrEmpty(task.StationName))
                            issues.Add($"工序 {processStep.ProcessStepName} 的工位名称为空");
                        
                        if (task.PlannedQuantity <= 0)
                            issues.Add($"工序 {processStep.ProcessStepName} 的计划数量无效");
                    }
                }
                else
                {
                    issues.Add($"工序 {processStep.ProcessStepName} 没有任务数据");
                }
            }

            // 显示检查结果
            var message = "数据字段检查结果:\n\n";
            if (issues.Count == 0)
            {
                message += "✅ 所有数据字段都正常\n";
                message += $"总任务数: {totalTasks}";
            }
            else
            {
                message += "❌ 发现以下问题:\n";
                foreach (var issue in issues)
                {
                    message += $"• {issue}\n";
                }
                message += $"\n总任务数: {totalTasks}";
            }

            System.Windows.MessageBox.Show(message, "数据字段检查", System.Windows.MessageBoxButton.OK, 
                issues.Count == 0 ? System.Windows.MessageBoxImage.Information : System.Windows.MessageBoxImage.Warning);
        }

        /// <summary>
        /// 检查任务字典状态
        /// </summary>
        private void CheckTaskDictionary()
        {
            System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] === 任务字典状态检查开始 ===");
            
            var message = "任务字典状态检查:\n\n";
            
            // 检查字典基本信息
            message += $"字典键数量: {_tasksByProcessStep.Count}\n";
            message += $"工序总数: {ProcessSteps.Count}\n\n";
            
            System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] 字典键数量: {_tasksByProcessStep.Count}");
            System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] 工序总数: {ProcessSteps.Count}");
            
            // 检查每个工序的任务状态
            foreach (var processStep in ProcessSteps)
            {
                var hasTasks = _tasksByProcessStep.ContainsKey(processStep.Id);
                var taskCount = hasTasks ? _tasksByProcessStep[processStep.Id].Count : 0;
                
                message += $"工序: {processStep.ProcessStepName} (ID: {processStep.Id})\n";
                message += $"  字典中有数据: {(hasTasks ? "是" : "否")}\n";
                message += $"  任务数量: {taskCount}\n";
                
                System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] 工序: {processStep.ProcessStepName} (ID: {processStep.Id})");
                System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}]   字典中有数据: {(hasTasks ? "是" : "否")}");
                System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}]   任务数量: {taskCount}");
                
                if (hasTasks && taskCount > 0)
                {
                    var tasks = _tasksByProcessStep[processStep.Id];
                    for (int i = 0; i < tasks.Count; i++)
                    {
                        var task = tasks[i];
                        message += $"    任务 {i + 1}: {task.TaskName} (ID: {task.TaskId})\n";
                        System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}]     任务 {i + 1}: {task.TaskName} (ID: {task.TaskId})");
                    }
                }
                message += "\n";
            }
            
            // 检查当前选中的工序
            if (SelectedProcessStep != null)
            {
                message += $"当前选中工序: {SelectedProcessStep.ProcessStepName} (ID: {SelectedProcessStep.Id})\n";
                var currentTaskCount = Tasks.Count;
                message += $"当前显示任务数量: {currentTaskCount}\n";
                
                System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] 当前选中工序: {SelectedProcessStep.ProcessStepName} (ID: {SelectedProcessStep.Id})");
                System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] 当前显示任务数量: {currentTaskCount}");
            }
            
            System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] === 任务字典状态检查结束 ===");
            
            System.Windows.MessageBox.Show(message, "任务字典状态检查", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Information);
        }

        private void AddTask()
        {
            try
            {
                if (SelectedProcessStep == null)
                {
                    System.Windows.MessageBox.Show("请先选择一个工序", "提示", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Information);
                    return;
                }

                var addTaskDialog = new WPF_MVVM_Test.MVVM_View.ProductionOrder.AddTaskDialog(
                    _originalOrder.Id, 
                    SelectedProcessStep.Id, 
                    ProcessRouteNumber,
                    ProcessRouteName,
                    PlanQuantity,
                    PlanStartTime,
                    PlanEndTime);

                if (System.Windows.Application.Current.MainWindow != null)
                {
                    addTaskDialog.Owner = System.Windows.Application.Current.MainWindow;
                }

                if (addTaskDialog.ShowDialog() == true)
                {
                    var newTask = addTaskDialog.GetNewTask();
                    if (newTask != null)
                    {
                        // 设置序号
                        newTask.SequenceNo = Tasks.Count + 1;
                        
                        // 添加到任务列表
                        Tasks.Add(newTask);
                        
                        // 确保当前工序的任务在字典中
                        if (!_tasksByProcessStep.ContainsKey(SelectedProcessStep.Id))
                        {
                            _tasksByProcessStep[SelectedProcessStep.Id] = new ObservableCollection<ProcessTaskModel>();
                        }
                        
                        // 将新任务也添加到字典中，并更新字典中的任务集合
                        _tasksByProcessStep[SelectedProcessStep.Id] = new ObservableCollection<ProcessTaskModel>(Tasks);
                        
                        System.Windows.MessageBox.Show("任务添加成功", "成功", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Information);
                    }
                }
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show($"添加任务失败：{ex.Message}", "错误", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Error);
            }
        }

        private void EditTask(ProcessTaskModel? task)
        {
            if (task == null) return;

            try
            {
                // TODO: 实现编辑任务功能
                System.Windows.MessageBox.Show("编辑任务功能待实现", "提示", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Information);
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show($"编辑任务失败：{ex.Message}", "错误", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Error);
            }
        }

        private void DeleteTask(ProcessTaskModel? task)
        {
            if (task == null) return;

            try
            {
                var result = System.Windows.MessageBox.Show("确定要删除这个任务吗？", "确认删除", 
                    System.Windows.MessageBoxButton.YesNo, System.Windows.MessageBoxImage.Question);
                
                if (result == System.Windows.MessageBoxResult.Yes)
                {
                    // 从当前任务列表中删除
                    Tasks.Remove(task);
                    
                    // 重新排序序号
                    for (int i = 0; i < Tasks.Count; i++)
                    {
                        Tasks[i].SequenceNo = i + 1;
                    }
                    
                    // 更新字典中的任务集合
                    if (SelectedProcessStep != null)
                    {
                        _tasksByProcessStep[SelectedProcessStep.Id] = new ObservableCollection<ProcessTaskModel>(Tasks);
                    }
                    
                    System.Windows.MessageBox.Show("任务删除成功", "成功", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Information);
                }
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show($"删除任务失败：{ex.Message}", "错误", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Error);
            }
        }
        #endregion

        public ObservableCollection<BomItem> BomItems { get; set; } = new ObservableCollection<BomItem>();

        public bool DialogResult
        {
            get => _dialogResult;
            set { _dialogResult = value; OnPropertyChanged(); }
        }

        private void FillBasicInfo()
        {
            if (_originalOrder != null)
            {
                OrderNumber = _originalOrder.OrderNumber ?? string.Empty;
                OrderName = _originalOrder.OrderName ?? _originalOrder.ProductName ?? string.Empty;
                ProductNumber = _originalOrder.ProductNumber ?? string.Empty;
                Specification = _originalOrder.Specification ?? string.Empty;
                Unit = _originalOrder.Unit ?? string.Empty;
                BomCode = _originalOrder.BomCode ?? string.Empty;
                PlanQuantity = _originalOrder.PlanQuantity;
                
                // 设置时间，如果原工单有计划时间，使用原时间，否则使用默认值
                if (_originalOrder.PlanStartTime.HasValue)
                {
                    PlanStartTime = _originalOrder.PlanStartTime.Value;
                    StartTime = _originalOrder.PlanStartTime.Value;
                }
                else
                {
                    PlanStartTime = DateTime.Today;
                    StartTime = DateTime.Today;
                }
                
                if (_originalOrder.PlanEndTime.HasValue)
                {
                    PlanEndTime = _originalOrder.PlanEndTime.Value;
                    EndTime = _originalOrder.PlanEndTime.Value;
                }
                else
                {
                    PlanEndTime = DateTime.Today.AddDays(7);
                    EndTime = DateTime.Today.AddDays(7);
                }
                
                // 清空备注，让用户输入新的排产备注
                Remark = string.Empty;
            }
        }

        private async Task LoadProcessStepsAsync()
        {
            try
            {
                var response = await _processService.GetProductionOrderProcessesAsync(_originalOrder.Id);
                
                if (response.IsSuc && response.Data?.Data != null)
                {
                    ProcessSteps.Clear();
                    
                    foreach (var step in response.Data.Data)
                    {
                        ProcessSteps.Add(step);
                    }
                    
                    // 默认选中第一个工序
                    if (ProcessSteps.Count > 0)
                    {
                        SelectedProcessStep = ProcessSteps.First();
                    }
                }
                else
                {
                    // 如果API没有返回数据，使用测试数据确保界面正常显示
                    LoadTestProcessSteps();
                }
            }
            catch (Exception ex)
            {
                // 如果API调用失败，使用测试数据确保界面正常显示
                LoadTestProcessSteps();
            }
        }

        /// <summary>
        /// 加载测试工序数据作为回退机制
        /// </summary>
        private void LoadTestProcessSteps()
        {
            ProcessSteps.Clear();
            
            var testSteps = new[]
            {
                new ProcessStepModel { Id = "1", ProcessStepName = "原料预处理" },
                new ProcessStepModel { Id = "2", ProcessStepName = "主加工" },
                new ProcessStepModel { Id = "3", ProcessStepName = "精加工" },
                new ProcessStepModel { Id = "4", ProcessStepName = "检验" },
                new ProcessStepModel { Id = "5", ProcessStepName = "包装" }
            };
            
            foreach (var step in testSteps)
            {
                ProcessSteps.Add(step);
            }
            
            // 默认选中第一个工序
            if (ProcessSteps.Count > 0)
            {
                SelectedProcessStep = ProcessSteps.First();
            }
        }

        private async Task LoadProcessRoutingAsync()
        {
            try
            {
                var response = await _productionOrderService.GetProductionOrderRoutingAsync(_originalOrder.Id);
                
                if (response.IsSuc && response.Data != null)
                {
                    ProcessRouteNumber = response.Data.ProcessRouteNumber ?? string.Empty;
                    ProcessRouteName = response.Data.ProcessRouteName ?? string.Empty;
                }
                else
                {
                    // 如果API没有返回数据，使用测试数据
                    LoadTestProcessRouting();
                }
            }
            catch (Exception ex)
            {
                // 如果API调用失败，使用测试数据
                LoadTestProcessRouting();
            }
        }

        /// <summary>
        /// 加载测试工艺路线数据作为回退机制
        /// </summary>
        private void LoadTestProcessRouting()
        {
            ProcessRouteNumber = "GY20241201001";
            ProcessRouteName = "新产品工艺路线";
        }

        private async Task LoadTasksAsync()
        {
            try
            {
                if (SelectedProcessStep != null)
                {
                    var response = await _processService.GetProcessStepTasksAsync(
                        SelectedProcessStep.Id, _originalOrder.Id);
                    
                    if (response.IsSuc && response.Data?.Data != null)
                    {
                        Tasks.Clear();
                        
                        foreach (var task in response.Data.Data)
                        {
                            Tasks.Add(task);
                        }
                        
                        // 将API返回的任务保存到字典中
                        _tasksByProcessStep[SelectedProcessStep.Id] = new ObservableCollection<ProcessTaskModel>(Tasks);
                    }
                    else
                    {
                        // 如果API没有返回数据，清空任务列表
                        Tasks.Clear();
                        
                        // 确保字典中有该工序的条目
                        if (!_tasksByProcessStep.ContainsKey(SelectedProcessStep.Id))
                        {
                            _tasksByProcessStep[SelectedProcessStep.Id] = new ObservableCollection<ProcessTaskModel>();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show($"加载任务信息失败: {ex.Message}", "错误", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Error);
                // 发生异常时清空任务列表
                Tasks.Clear();
                
                // 确保字典中有该工序的条目
                if (SelectedProcessStep != null && !_tasksByProcessStep.ContainsKey(SelectedProcessStep.Id))
                {
                    _tasksByProcessStep[SelectedProcessStep.Id] = new ObservableCollection<ProcessTaskModel>();
                }
            }
        }

        private async Task LoadMaterialsAsync()
        {
            try
            {
                System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] === 开始加载物料信息 ===");
                System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] 工单ID: {_originalOrder.Id}");
                System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] 工单编号: {_originalOrder.OrderNumber}");
                System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] 工单名称: {_originalOrder.OrderName}");
                
                var response = await _productionOrderService.GetProductionOrderMaterialListAsync(_originalOrder.Id);
                
                System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] API响应结果:");
                System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}]   IsSuc: {response.IsSuc}");
                System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}]   Code: {response.Code}");
                System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}]   Msg: {response.Msg}");
                System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}]   Data是否为null: {response.Data == null}");
                
                if (response.IsSuc && response.Data?.Materials != null)
                {
                    System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] 物料信息加载成功，物料数量: {response.Data.Materials.Count}");
                    
                    BomItems.Clear();
                    
                    foreach (var material in response.Data.Materials)
                    {
                        System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] 处理物料: {material.MaterialName} (编号: {material.MaterialNumber})");
                        
                        BomItems.Add(new BomItem
                        {
                            MaterialName = material.MaterialName,
                            MaterialNumber = material.MaterialNumber,
                            Specification = material.Specification,
                            RequiredQuantity = (decimal)material.EstimatedUsage,
                            Unit = material.Unit,
                            AvailableQuantity = 0,
                            Status = "待确认"
                        });
                    }
                    
                    System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] 物料信息处理完成，BomItems数量: {BomItems.Count}");
                }
                else
                {
                    System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] 物料信息API调用失败: {response.Msg}");
                    System.Windows.MessageBox.Show($"加载物料信息失败: {response.Msg}", "错误", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Error);
                    
                    // 清空物料列表，不显示测试数据
                    BomItems.Clear();
                }
                
                System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] === 物料信息加载结束 ===");
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] 加载物料信息异常: {ex.Message}");
                System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] 异常堆栈: {ex.StackTrace}");
                System.Windows.MessageBox.Show($"加载物料信息失败: {ex.Message}", "错误", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Error);
                
                // 清空物料列表，不显示测试数据
                BomItems.Clear();
            }
        }

        /// <summary>
        /// 预览将要发送的数据
        /// </summary>
        private void PreviewData()
        {
            try
            {
                // 收集所有工序的任务数据（与ConfirmSchedule相同的逻辑）
                var allTasks = new List<WorkOrderTaskRequest>();
                
                foreach (var processStep in ProcessSteps)
                {
                    if (_tasksByProcessStep.ContainsKey(processStep.Id))
                    {
                        var tasks = _tasksByProcessStep[processStep.Id];
                        
                        foreach (var task in tasks)
                        {
                            // 确保时间字段有有效值
                            var planStartTime = task.PlannedStartTime ?? PlanStartTime;
                            var planEndTime = task.PlannedEndTime ?? PlanEndTime;
                            
                            // 如果结束时间早于开始时间，调整结束时间
                            if (planEndTime <= planStartTime)
                            {
                                planEndTime = planStartTime.AddHours(1);
                            }

                            // 验证GUID字段
                            var processRouteId = Guid.TryParse(ProcessRouteNumber, out var routeGuid) ? routeGuid : Guid.NewGuid();
                            var processStepId = Guid.TryParse(processStep.Id, out var stepGuid) ? stepGuid : Guid.NewGuid();

                            // 计算计划时长（小时）
                            var planDuration = (decimal)(planEndTime - planStartTime).TotalHours;
                            if (planDuration <= 0)
                            {
                                planDuration = 1.0m; // 默认1小时
                            }

                            var workOrderTask = new WorkOrderTaskRequest
                            {
                                SequenceNumber = task.SequenceNo,
                                TaskNumber = string.IsNullOrEmpty(task.TaskId) ? $"TASK_{processStep.Id}_{DateTime.Now:yyyyMMddHHmmss}" : task.TaskId,
                                TaskName = string.IsNullOrEmpty(task.TaskName) ? $"{processStep.ProcessStepName}任务" : task.TaskName,
                                ProductionOrderId = _originalOrder.Id,
                                StationName = string.IsNullOrEmpty(task.StationName) ? "默认工位" : task.StationName,
                                ProcessCode = processStep.ProcessStepName,
                                ProcessName = processStep.ProcessStepName,
                                ProcessFlow = string.IsNullOrEmpty(ProcessRouteName) ? "默认工艺流程" : ProcessRouteName,
                                ProcessType = string.IsNullOrEmpty(task.ProcessType) ? "默认类型" : task.ProcessType,
                                TaskColor = string.IsNullOrEmpty(task.TaskColor) ? "#1890FF" : task.TaskColor,
                                PlanQuantity = task.PlannedQuantity > 0 ? task.PlannedQuantity : PlanQuantity,
                                PlanStartTime = planStartTime,
                                PlanEndTime = planEndTime,
                                PlanDuration = planDuration,
                                Status = string.IsNullOrEmpty(task.Status) ? "待开工" : task.Status,
                                ProcessRouteId = processRouteId,
                                ProcessStepId = processStepId,
                                Priority = task.Priority > 0 ? task.Priority : 4,
                                Remarks = string.IsNullOrEmpty(task.Remarks) ? Remark : task.Remarks
                            };
                            
                            allTasks.Add(workOrderTask);
                        }
                    }
                }

                // 如果没有任务数据，创建默认任务
                if (allTasks.Count == 0)
                {
                    foreach (var processStep in ProcessSteps)
                    {
                        var processRouteId = Guid.TryParse(ProcessRouteNumber, out var routeGuid) ? routeGuid : Guid.NewGuid();
                        var processStepId = Guid.TryParse(processStep.Id, out var stepGuid) ? stepGuid : Guid.NewGuid();
                        
                        var defaultTask = new WorkOrderTaskRequest
                        {
                            SequenceNumber = allTasks.Count + 1,
                            TaskNumber = $"TASK_{processStep.Id}_{DateTime.Now:yyyyMMddHHmmss}",
                            TaskName = $"{processStep.ProcessStepName}任务",
                            ProductionOrderId = _originalOrder.Id,
                            StationName = "默认工位",
                            ProcessCode = processStep.ProcessStepName,
                            ProcessName = processStep.ProcessStepName,
                            ProcessFlow = string.IsNullOrEmpty(ProcessRouteName) ? "默认工艺流程" : ProcessRouteName,
                            ProcessType = "默认类型",
                            TaskColor = "#1890FF",
                            PlanQuantity = PlanQuantity,
                            PlanStartTime = PlanStartTime,
                            PlanEndTime = PlanEndTime,
                            PlanDuration = (decimal)(PlanEndTime - PlanStartTime).TotalHours,
                            Status = "待开工",
                            ProcessRouteId = processRouteId,
                            ProcessStepId = processStepId,
                            Priority = 4,
                            Remarks = "系统自动生成的默认任务"
                        };
                        
                        allTasks.Add(defaultTask);
                    }
                }

                // 创建批量添加请求
                var batchRequest = new BatchAddWorkOrderTasksRequest
                {
                    Tasks = allTasks
                };

                // 序列化为JSON
                var jsonOptions = new System.Text.Json.JsonSerializerOptions
                {
                    PropertyNamingPolicy = System.Text.Json.JsonNamingPolicy.CamelCase,
                    WriteIndented = true
                };
                var jsonString = System.Text.Json.JsonSerializer.Serialize(batchRequest, jsonOptions);

                // 显示预览
                var previewMessage = $"数据预览:\n\n总任务数: {allTasks.Count}\n\n";
                previewMessage += "任务详情:\n";
                
                for (int i = 0; i < allTasks.Count; i++)
                {
                    var task = allTasks[i];
                    previewMessage += $"\n任务 {i + 1}:\n";
                    previewMessage += $"  序号: {task.SequenceNumber}\n";
                    previewMessage += $"  任务编号: {task.TaskNumber}\n";
                    previewMessage += $"  任务名称: {task.TaskName}\n";
                    previewMessage += $"  生产工单ID: {task.ProductionOrderId}\n";
                    previewMessage += $"  工位名称: {task.StationName}\n";
                    previewMessage += $"  工序代码: {task.ProcessCode}\n";
                    previewMessage += $"  工序名称: {task.ProcessName}\n";
                    previewMessage += $"  工艺流程: {task.ProcessFlow}\n";
                    previewMessage += $"  工序类型: {task.ProcessType}\n";
                    previewMessage += $"  任务颜色: {task.TaskColor}\n";
                    previewMessage += $"  计划数量: {task.PlanQuantity}\n";
                    previewMessage += $"  计划开始时间: {task.PlanStartTime}\n";
                    previewMessage += $"  计划结束时间: {task.PlanEndTime}\n";
                    previewMessage += $"  计划时长: {task.PlanDuration}\n";
                    previewMessage += $"  状态: {task.Status}\n";
                    previewMessage += $"  工艺路线ID: {task.ProcessRouteId}\n";
                    previewMessage += $"  工序步骤ID: {task.ProcessStepId}\n";
                    previewMessage += $"  优先级: {task.Priority}\n";
                    previewMessage += $"  备注: {task.Remarks}\n";
                }

                previewMessage += $"\n\nJSON格式:\n{jsonString}";

                // 使用滚动文本框显示
                var scrollViewer = new System.Windows.Controls.ScrollViewer
                {
                    VerticalScrollBarVisibility = System.Windows.Controls.ScrollBarVisibility.Auto,
                    HorizontalScrollBarVisibility = System.Windows.Controls.ScrollBarVisibility.Auto,
                    MaxHeight = 600,
                    MaxWidth = 800
                };

                var textBox = new System.Windows.Controls.TextBox
                {
                    Text = previewMessage,
                    IsReadOnly = true,
                    TextWrapping = System.Windows.TextWrapping.Wrap,
                    FontFamily = new System.Windows.Media.FontFamily("Consolas"),
                    FontSize = 10
                };

                scrollViewer.Content = textBox;

                var window = new System.Windows.Window
                {
                    Title = "数据预览",
                    Width = 850,
                    Height = 650,
                    WindowStartupLocation = System.Windows.WindowStartupLocation.CenterOwner,
                    Content = scrollViewer
                };

                if (System.Windows.Application.Current.MainWindow != null)
                {
                    window.Owner = System.Windows.Application.Current.MainWindow;
                }

                window.ShowDialog();
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show($"预览数据时发生错误: {ex.Message}", "错误", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Error);
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;
        protected virtual void OnPropertyChanged([System.Runtime.CompilerServices.CallerMemberName] string propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    public class BomItem
    {
        public string MaterialName { get; set; } = string.Empty;
        public string MaterialNumber { get; set; } = string.Empty;
        public string Specification { get; set; } = string.Empty;
        public decimal RequiredQuantity { get; set; }
        public string Unit { get; set; } = string.Empty;
        public decimal AvailableQuantity { get; set; }
        public string Status { get; set; } = string.Empty;
    }
}
